<template>
  <div class="roles">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-button type="primary" plain @click="handleaddRoler">添加角色</el-button>

    <el-table class="mt-15" :data="roleList" border style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <!-- 第一个循环加给最外层的el-row -->
          <el-row v-for="firtChildItem in scope.row.children" :key="firtChildItem.id">
            <!-- 总体分成两部分，一份小的占4份，大的占20份。4份中的内容放的是，第一个children中的每一项的authName -->
            <el-col :span="4">
              <el-tag
                closable
                @close="handleClose(scope.row, firtChildItem.id)"
              >{{firtChildItem.authName}}</el-tag>
              <!-- 判断什么时候出现右箭头？ -->
              <i class="el-icon-arrow-right" v-if="firtChildItem.children.length > 0"></i>
            </el-col>
            <el-col :span="20">
              <!-- 继续对20份的这块内容进行划分，又分为4份 和 20份 -->
              <!-- 第二个循环加给内层的el-row -->
              <el-row v-for="secondChildItem in firtChildItem.children" :key="secondChildItem.id">
                <el-col :span="4">
                  <el-tag
                    type="success"
                    closable
                    @close="handleClose(scope.row, secondChildItem.id)"
                  >{{secondChildItem.authName}}</el-tag>
                  <i class="el-icon-arrow-right" v-if="secondChildItem.children.length > 0"></i>
                </el-col>
                <el-col :span="20">
                  <!-- 第三个循环直接加给tag组件就行了 -->
                  <el-tag
                    type="danger"
                    v-for="thirdChildItem in secondChildItem.children"
                    :key="thirdChildItem.id"
                    closable
                    @close="handleClose(scope.row, thirdChildItem.id)"
                  >{{thirdChildItem.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" v-if="scope.row.children.length<=0">该角色没有分配权限，请前往分配！</el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="roleName" label="角色名称"></el-table-column>
      <el-table-column prop="roleDesc" label="描述"></el-table-column>
      <el-table-column label="操作">
        <!-- 1.3 表格直接渲染数据不需要使用作用域插槽，如果在表格里面需要放标签或者其他组件的时候，就需要使用作用域插槽 -->
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
          <!-- 4.4 通过scope对象的row属性，可以拿到点击的那一行的表格数据对象 -->
          <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)"></el-button>
          <!-- 9.2 点击授权按钮 -->
          <el-button type="warning" icon="el-icon-check" circle @click="handleGrantRight(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加弹框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogFormVisible" :before-close="closeDialog">
      <el-form :model="addForm" :rules="myrules" ref="addRef">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="addForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelselector('add')">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑弹框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" :rules="editrules" ref="editRef">
        <el-form-item label="角色名称" :label-width="formLabelWidth" prop="roleName">
          <el-input v-model="editForm.roleName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" :label-width="formLabelWidth" prop="roleDesc">
          <el-input v-model="editForm.roleDesc" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelselector('edit')">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 角色授权弹框 -->
    <el-dialog title="授权角色" :visible.sync="grantDialogFormVisible">
      <!-- 10.3 添加树形控件 -->
      <div class="tree-box">
        <el-tree
          :data="rightList"
          ref="tree"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectedIds"
          :props="defaultProps">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="grantDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmGrant">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRoles,
  deleteRoleRight,
  deleteRoler,
  addRoler,
  editRoler,
  getRightList,
  grantRole
} from '@/api'
export default {
  data () {
    return {
      roleList: [],
      formLabelWidth: '120px',
      // 添加的数据:
      addDialogFormVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑的数据:
      editDialogFormVisible: false,
      editForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      myrules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        roleDesc: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      editrules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 授权信息:
      rightList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      grantDialogFormVisible: false,
      selectedIds: [], // 默认选中节点的id数组
      currentRole: {} // 10.11
    }
  },
  created () {
    this.initTable()
  },
  methods: {
    initTable () {
      getRoles().then(res => {
        this.roleList = res.data
      })
    },
    handleClose (row, rid) {
      deleteRoleRight(row.id, rid).then(res => {
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
          row.children = res.data
        } else {
          this.$message.error(res.meta.msg)
        }
      })
    },
    handleaddRoler () {
      this.addDialogFormVisible = true
    },
    confirmAdd () {
      this.$refs.addRef.validate(isPass => {
        if (isPass) {
          addRoler(this.addForm).then(res => {
            if (res.meta.status === 201) {
              this.$message.success('添加用户成功')
              this.addDialogFormVisible = false
              // 清空表单
              this.addForm = {}
              // 刷新数据
              this.initTable()
            } else {
              this.$message.error(res.meta.msg)
            }
          })
        } else {
          // 弹错误的提示信息
          this.$message.error('请正确填写表单信息')
        }
      })
    },
    handleEdit (row) {
      // console.log(row)
      this.editDialogFormVisible = true
      // 给编辑弹框的表单赋值:
      this.editForm.roleId = row.id
      this.editForm.roleName = row.roleName
      this.editForm.roleDesc = row.roleDesc
    },
    confirmEdit () {
      this.$refs.editRef.validate(isPass => {
        if (isPass) {
          editRoler(this.editForm.roleId, {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc
          }).then(res => {
            if (res.meta.status === 200) {
              this.$message.success(res.meta.msg)
              this.editDialogFormVisible = false
              this.initTable()
            } else {
              this.$message.error(res.meta.msg)
            }
          })
        } else {
          this.$message.error('请输入正确的表单信息')
        }
      })
    },
    handleDelete (row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteRoler(row.id).then(res => {
            if (res.meta.status === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.initTable()
            } else {
              this.$message.error(res.meta.meg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    closeDialog (done) {
      this.addForm = {}
      this.$refs.addRef.clearValidate()
      done()
    },
    cancelselector (selector) {
      this[selector + 'DialogFormVisible'] = false
      this[selector + 'Form'] = {}
      this.$refs[selector + 'Ref'].clearValidate()
    },
    handleGrantRight (row) {
      this.grantDialogFormVisible = true
      // 暂存角色的信息:
      this.currentRole = row
      this.selectedIds = []
      // 分别遍历数据,最后将第三层的数据id取到push进数组
      row.children.forEach(firstItem => {
        if (firstItem.children && firstItem.children.length > 0) {
          firstItem.children.forEach(secondItem => {
            if (secondItem.children && secondItem.children.length > 0) {
              secondItem.children.forEach(thirdItem => {
                this.selectedIds.push(thirdItem.id)
              })
            }
          })
        }
        this.getTreeData()
      })
    },
    confirmGrant () {
      let checkedNodes = this.$refs.tree.getCheckedNodes()
      let tempArr = checkedNodes.map(item => item.id + ',' + item.pid)
      let repeatedArr = tempArr.join(',').split(',')
      let myset = new Set(repeatedArr)
      let idsArr = [...myset]
      let idsStr = idsArr.join(',')

      grantRole(this.currentRole.id, idsStr)
        .then(res => {
          if (res.meta.status === 200) {
            this.grantDialogFormVisible = false
            this.initTable()
            this.$message.success(res.meta.msg)
          } else {
            this.$message.error(res.meta.msg)
          }
        })
    },
    // 获树形数据:
    getTreeData () {
      getRightList('tree')
        .then(res => {
          this.rightList = res.data
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag{
  margin: 5px;
}
.tree-box {
  height: 300px;
  overflow: auto;
}
</style>
